package com.reach.redis.aspect;

import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import com.google.gson.Gson;
import com.reach.redis.manager.SpringContextUtil;


public class CacheAspect {
	
	private static final Logger logger = LoggerFactory.getLogger(CacheAspect.class);
	
	private static final Executor executor = Executors.newFixedThreadPool(2);
	
	
    public Object readCache(String key) {
    	try {
    		
    		//Assert.notEmpty(key, "'key' must not be empty");
    		if(logger.isDebugEnabled()) {
    			logger.debug("Cache key is {}.",String.valueOf(key));
    		}
    		RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) SpringContextUtil.getBean("redis");
    		return redisTemplate.opsForValue().get(key);
    	}catch(Exception e ) {
    		logger.error(e.getMessage());
    	}
    	return null;
    }
    
    public boolean writeCache(Object value,String  key) {
    	try {
    		//Assert.notEmpty(key, "'key' must not be empty");
    		if(logger.isDebugEnabled()) {
    			Gson gson = new Gson();
    			logger.debug("Cache key is {}:{}.",String.valueOf(key),gson.toJson(value));
    		}
    		RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) SpringContextUtil.getBean("redis");
    		redisTemplate.opsForValue().set(key,value);
    		return true;
    	}catch(Exception e ) {
    		logger.error(e.getMessage());
    	}
    	return false;
    }
    
    public boolean delete(String module,String key,boolean sync) {
    	try {
	    	if(StringUtils.isEmpty(key) || "null".equals(key)) {
	    		return false;
	    	}
	    	RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) SpringContextUtil.getBean("redis");
	    	redisTemplate.execute(new RedisCallback<Object>() {
				@Override
				public Object doInRedis(RedisConnection connection) {
					
						Set<byte[]> keys = connection.keys(("*"+key + "*").getBytes());
						for(byte[] by : keys){
							String str = new String(by,StandardCharsets.UTF_8);
							if(str.startsWith(module)) {
								 connection.del(by);
				    		}
						}
						return null;
				}
	
			});
    	}catch(Exception e) {
    		logger.error(e.getMessage());
    	}
    	return false;
    }
    
    class CacheThread implements Runnable{

		@Override
		public void run() {
			
		}
    	
    }
    
 
}